package controllers

import (
	"fly/resp"
	"fly/schema"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/context"
	"github.com/pkg/errors"
)

type ErrorController struct {
	beego.Controller
}

func (c *ErrorController) Error404() {
	c.Data["json"] = resp.StatusResult{
		Code:    404,
		Status:  schema.FailStatus,
		TraceId: c.Ctx.Request.Header.Get(schema.TrackKey),
		Message: "not found path",
	}
	_ = c.ServeJSON()
	c.Abort("404")
}

// Error500
// 接收处理c.Abort("500") 的异常
func (c *ErrorController) Error500() {
	c.Data["json"] = resp.StatusResult{
		Code:    500,
		Status:  schema.FailStatus,
		TraceId: c.Ctx.Request.Header.Get(schema.TrackKey),
		Message: "服务器内部异常，请联系管理员",
	}
	_ = c.ServeJSON()
	c.StopRun()
}

// ErrorAuth
// 接收处理c.Abort("Auth") 的异常
func (c *ErrorController) ErrorAuth() {
	c.Data["json"] = resp.StatusResult{
		Code:    401,
		Status:  schema.ErrAuth,
		TraceId: c.Ctx.Request.Header.Get(schema.TrackKey),
		Message: "权限异常",
	}
	_ = c.ServeJSON()
	c.Abort("Auth")
}

func Error500Handle(ctx *context.Context, config *beego.Config) {
	if err := recover(); err != nil {
		wrapErr := errors.New(fmt.Sprintf("=== internal %v err >>>", err))
		cause := errors.WithStack(wrapErr)
		url := ctx.Request.RequestURI
		if err == "404" {
			logs.Error("%s cause 404", url)
			return
		}
		if err == "Auth" {
			logs.Error("%s no auth stack %+v", url, cause)
			return
		}
		if err == "Abort" {
			logs.Error("%s abort handle", url)
			return
		}
		logs.Error("%s cause err stack %+v", url, cause)
		_ = ctx.JSONResp(resp.StatusResult{
			Code:    500,
			Status:  schema.FailStatus,
			TraceId: ctx.Request.Header.Get(schema.TrackKey),
			Message: fmt.Sprintf("请求：%s =>服务器内部异常:%v", url, err),
		})
	}
}
